<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Activity;
use App\Models\Participant;
use App\Models\ParticipantActivity;
use App\Models\ParticipantSurvey;
use App\Models\Survey;
use App\Org\Developer\Helper;
use App\Org\Developer\JsonReturnInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * @author 陈玉琦
 */
class ParticipantController extends Controller
{
    /**
     * 报名参加活动（游戏或者调查）
     * 将参与者信息写入数据表
     * 信息分为普通模式和微信模式两种
     *
     * @param Request $request
     * @return array
     */

    public function store(Request $request)
    {
        // 参加的是哪一期活动或者调查
        $activity_id = $request->input('activity_id', 0);
        $survey_id = $request->input('survey_id', 0);
        $play_id = $request->input('play_id', 0);
        $type = '';
        $game_bg_url = '';// 游戏背景图片；
        // 3个都无效，错误
        if (Helper::idInvalid($activity_id) && Helper::idInvalid($survey_id) && Helper::idInvalid($play_id)) {
            return JsonReturnInfo::infoFailure('必须选择要参加哪一期的活动、调查或者剧本.');
        }
        // 表明参加的是活动
        else if (!Helper::idInvalid($activity_id)) {
            $type = 'activity';
            $activityModel = Activity::select(['id', 'game_bg_url'])->where(['id' => $activity_id])->first();
            $game_bg_url = $activityModel->game_bg_url;
        }
        // 表明参加的是调查
        else if (!Helper::idInvalid($survey_id)) {
            $type = 'survey';
        }
        // 表明参加的是剧本
        else if (!Helper::idInvalid($play_id)) {
            $type = 'play';
        }

        // 如果有参与者 participant_id，说明参与者信息已经写入过
        // 前端验证，cookie 里有 participant_id 则不再填写个人信息（也就是个人信息只在 第一次参加活动 或者 cookie过期 时需要填写）
        if (intval($participant_id = $request->input('participant_id', '')) !== 0) {
            // 没有填写个人信息

            // 检查 $participant_id 是否有效
            if (Helper::idInvalid($participant_id)) {
                return JsonReturnInfo::ID_ERROR;
            }

            try {
                // 检查此人是否存在
                $participantModel = Participant::where(['id' => $participant_id])->first();
                // 存在
                if (isset($participantModel) && $participantModel->id) {
                    // 是否参加过该活动或者调查，不能重复参加
                    if ($type == 'activity') {
                        $existedModel = ParticipantActivity::where(['participant_id' => $participant_id, 'activity_id' => $activity_id])->first();
                    } else if ($type == 'survey') {
                        $existedModel = ParticipantSurvey::where(['participant_id' => $participant_id, 'survey_id' => $survey_id])->first();
                    } else if ($type == 'play') {
                        $existedModel = ParticipantActivity::where(['participant_id' => $participant_id, 'play_id' => $play_id])->first();
                    }
                    if (isset($existedModel) && $existedModel->participant_id) {
                        return JsonReturnInfo::infoFailure('已参加过，不能重复参加.', ['game_bg_url' => $game_bg_url]);
                    }

                    // 把参与的活动写入 participant_activities 表
                    if ($type == 'activity') {
                        $createModel = ParticipantActivity::create([
                            'participant_id' => $participantModel->id,
                            'activity_id' => $activity_id
                        ]);
                    }
                    // 把参与的调查写入 participant_surveys 表
                    else if ($type == 'survey') {
                        $createModel = ParticipantSurvey::create([
                            'participant_id' => $participantModel->id,
                            'survey_id' => $survey_id
                        ]);
                    }
                    // 把参与的剧本写入 participant_activities 表
                    else if ($type == 'play') {
                        $createModel = ParticipantSurvey::create([
                            'participant_id' => $participantModel->id,
                            'play_id' => $play_id
                        ]);
                    }

                    // 写入成功
                    if (isset($createModel) && $createModel->participant_id) {
                        return JsonReturnInfo::infoSuccess('参加成功.', [
                            'participant_id' => $participantModel->id,
                            'game_bg_url' => $game_bg_url
                        ]);
                    }
                    return JsonReturnInfo::infoFailure('参加失败.', ['game_bg_url' => $game_bg_url]);
                } else {
                    return JsonReturnInfo::infoFailure('指定参与者 participant_id 不存在，需要参与者填写个人信息.', ['game_bg_url' => $game_bg_url]);
                }
            } catch (\Exception $e) {
                return JsonReturnInfo::infoCatch($e);
            }
        }

        // 微信模式的信息
        if (!empty($request->input('openid', ''))) {
            // 参与者的微信openID
            $userInfo['openid'] = $request->input('openid', '');
            // 参与者的微信昵称
            $nickname = $request->input('nickname', '');
            // 昵称中如果有表情符号
            if ($nickname !== '') {
                $userInfo['nickname'] = urlencode($nickname);
                $userInfo['nickname_raw'] = $nickname;
            }
            // 参与者的微信头像
            $userInfo['headimgurl'] = $request->input('headimgurl', '');

            // 参与者的性别
            $userInfo['sex'] = $request->input('sex', 3);//前台得到sex：0，也会传递3过来，表示未知。
        }
        // 普通模式的信息
        else {
            // 参与者的姓名
            $userInfo['username'] = $request->input('username', '');
            // 参与者的年龄
            // $userInfo['age'] = $request->input('age', 0);
            // 参与者的身份证号码
            // $userInfo['id_no'] = $request->input('id_no', '');
            // 参与者的手机号码
            $userInfo['mobile'] = $request->input('mobile', '');
            // 参与者的电子邮箱
            // $userInfo['email'] = $request->input('email', '');
        }

        // 参与者的性别
        // $userInfo['sex'] = $request->input('sex', 3);//前台得到sex：0，也会传递3过来，表示未知。

        // 数据的验证（略），前端js进行验证即可，避免重复验证影响运行效率。

        try {
            // 根据 openid 查询用户信息是否已经存在
            if (isset($userInfo['openid']) && !empty($userInfo['openid'])) {
                $participantModel = Participant::where(['openid' => $userInfo['openid']])->first();
                // 如果已存在，直接参加活动
                if (isset($participantModel) && $participantModel->id) {
                    // 更新用户微信信息
                    $participantModel->nickname = $userInfo['nickname'];
                    $participantModel->nickname_raw = $userInfo['nickname_raw'];
                    $participantModel->sex = $userInfo['sex'];
                    $participantModel->headimgurl = $userInfo['headimgurl'];
                    $participantModel->save();

                    // 是否参加过该 活动/调查，不能重复参加
                    if ($type == 'activity') {
                        $existedModel = ParticipantActivity::where(['participant_id' => $participantModel->id, 'activity_id' => $activity_id])->first();
                    } else if ($type == 'survey') {
                        $existedModel = ParticipantSurvey::where(['participant_id' => $participantModel->id, 'survey_id' => $survey_id])->first();
                    } else if ($type == 'play') {
                        $existedModel = ParticipantActivity::where(['participant_id' => $participant_id, 'play_id' => $play_id])->first();
                    }

                    if (isset($existedModel) && $existedModel->participant_id) {
                        return JsonReturnInfo::infoFailure('已参加过，不能重复参加.', ['game_bg_url' => $game_bg_url]);
                    }

                    // 把参与的活动写入 participant_activities 表
                    if ($type == 'activity') {
                        $createModel = ParticipantActivity::create([
                            'participant_id' => $participantModel->id,
                            'activity_id' => $activity_id
                        ]);
                    }
                    // 把参与的调查写入 participant_surveys 表
                    else if ($type == 'survey') {
                        $createModel = ParticipantSurvey::create([
                            'participant_id' => $participantModel->id,
                            'survey_id' => $survey_id
                        ]);
                    }
                    // 把参与的剧本写入 participant_activities 表
                    else if ($type == 'play') {
                        $createModel = ParticipantActivity::create([
                            'participant_id' => $participantModel->id,
                            'play_id' => $play_id
                        ]);
                    }

                    // 写入成功
                    if (isset($createModel) && $createModel->participant_id) {
                        return JsonReturnInfo::infoSuccess('参加成功.', [
                            'participant_id' => $participantModel->id,
                            'game_bg_url' => $game_bg_url
                        ]);
                    }
                    return JsonReturnInfo::infoFailure('参加失败.', ['game_bg_url' => $game_bg_url]);
                }
            }

            // 根据 username、id_no、mobile、email 查询用户信息是否已经存在
            // 根据 username、mobile 查询用户信息是否已经存在
            if (isset($userInfo['username']) && !empty($userInfo['username'])) {

                $participantModel = Participant::where(['mobile' => $userInfo['mobile']])->first();
                // 如果已存在，直接参加活动
                if (isset($participantModel) && $participantModel->id) {
                    if ($participantModel->username != $userInfo['username']) {
                        return JsonReturnInfo::infoFailure('参加失败，手机号被占用.', ['game_bg_url' => $game_bg_url]);
                    }

                    // 是否参加过该 活动/调查，不能重复参加
                    if ($type == 'activity') {
                        $existedModel = ParticipantActivity::where(['participant_id' => $participantModel->id, 'activity_id' => $activity_id])->first();
                    } else if ($type == 'survey') {
                        $existedModel = ParticipantSurvey::where(['participant_id' => $participantModel->id, 'survey_id' => $survey_id])->first();
                    } else if ($type == 'play') {
                        $existedModel = ParticipantActivity::where(['participant_id' => $participantModel->id, 'play_id' => $play_id])->first();
                    }
                    if (isset($existedModel) && $existedModel->participant_id) {
                        return JsonReturnInfo::infoFailure('已参加过，不能重复参加.', ['game_bg_url' => $game_bg_url]);
                    }

                    // 把参与的活动写入 participant_activities 表
                    if ($type == 'activity') {
                        $createModel = ParticipantActivity::create([
                            'participant_id' => $participantModel->id,
                            'activity_id' => $activity_id
                        ]);
                    }
                    // 把参与的调查写入 participant_surveys 表
                    else if ($type == 'survey') {
                        $createModel = ParticipantSurvey::create([
                            'participant_id' => $participantModel->id,
                            'survey_id' => $survey_id
                        ]);
                    }
                    // 把参与的剧本写入 participant_activities 表
                    else if ($type == 'play') {
                        $createModel = ParticipantActivity::create([
                            'participant_id' => $participantModel->id,
                            'play_id' => $play_id
                        ]);
                    }

                    // 写入成功
                    if (isset($createModel) && $createModel->participant_id) {
                        return JsonReturnInfo::infoSuccess('参加成功.', [
                            'participant_id' => $participantModel->id,
                            'game_bg_url' => $game_bg_url
                        ]);
                    }
                    return JsonReturnInfo::infoFailure('参加失败.', ['game_bg_url' => $game_bg_url]);
                }
            }

            // 执行到这里，说明该用户在 participants 表中还没有记录
            
            // 将参与者信息写入 participants 表
            $participantModel = Participant::create($userInfo);
            // 写入成功
            if (isset($participantModel) && $participantModel->id) {
                // 把参与的活动写入 participant_activities 表
                if ($type == 'activity') {
                    $createModel = ParticipantActivity::create([
                        'participant_id' => $participantModel->id,
                        'activity_id' => $activity_id
                    ]);
                }
                // 把参与的调查写入 participant_surveys 表
                else if ($type == 'survey') {
                    $createModel = ParticipantSurvey::create([
                        'participant_id' => $participantModel->id,
                        'survey_id' => $survey_id
                    ]);
                }
                // 把参与的剧本写入 participant_activities 表
                else if ($type == 'play') {
                    $createModel = ParticipantActivity::create([
                        'participant_id' => $participantModel->id,
                        'play_id' => $play_id
                    ]);
                }

                // 写入成功
                if (isset($createModel) && $createModel->participant_id) {
                    return JsonReturnInfo::infoSuccess('参加成功.', [
                        'participant_id' => $participantModel->id,
                        'game_bg_url' => $game_bg_url
                    ]);
                }
            }
            // 有一个写入失败
            return JsonReturnInfo::infoFailure('参与者信息写入失败，或者参加活动/调查失败.', ['game_bg_url' => $game_bg_url]);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 根据活动 activity_id 查询参与者信息
     *
     * @param $activity_id int|string 活动 activity_id
     * @return array
     */
    public function getByActivityId(Request $request, $activity_id = 0)
    {
        if (Helper::idInvalid($activity_id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 必须存在且必须是用户自己的资源
            $activityModel = Activity::select(['id', 'user_id', 'title'])->where(['id' => $activity_id])->first();
            if (!(isset($activityModel) && $activityModel->id)) {
                return JsonReturnInfo::infoFailure('要查询的活动不存在.');
            }
            if (!Helper::isUserSelfResource($user_id, $activityModel->user_id)) {
                return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            }

            // 根据 activity_id 查询参与者的 participants 信息
            return JsonReturnInfo::infoSuccess('获取数据成功.', Participant::getByActivityId($activity_id));
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 根据调查 survey_id 查询参与者信息
     *
     * @param $survey_id int|string 调查 survey_id
     * @return array
     */
    public function getBySurveyId(Request $request, $survey_id = 0)
    {
        if (Helper::idInvalid($survey_id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 必须存在且必须是用户自己的资源
            $surveyModel = Survey::select(['id', 'user_id', 'title', 'type'])->where(['id' => $survey_id])->first();
            if (!(isset($surveyModel) && $surveyModel->id)) {
                return JsonReturnInfo::infoFailure('要查询的调查不存在.');
            }
            if (!Helper::isUserSelfResource($user_id, $surveyModel->user_id)) {
                return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            }

            // 根据 survey_id 查询参与者的 participants 信息
            return JsonReturnInfo::infoSuccess('获取数据成功.', Participant::getBySurveyId($survey_id));
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 获取所有参加了某个用户发布的活动的参与者
     * 也就是根据 user_id 获取 participant_id
     * 怎么分组？每一期活动的参与者信息，还是参与者参加了那几期活动？
     * 暂时按前者处理。总体分成活动/调查两个部分。
     *
     * @param $user_id int|string 当前登录用户的 user_id
     * @return array
     */
    public function getActivityParticipantsByUserId($user_id = 0)
    {
        if (Helper::idInvalid($user_id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 根据 user_id 查询 activity_id，再根据 activity_id 查询参与者的 participants 信息
            $result = Participant::getByUserId($user_id, 'activity'); //->toArray();

            $data = [];
            foreach ($result as $item) {
                $item = json_decode(json_encode($item), true);
                $activity_id = $item['id'];
                if (isset($data[$item['id']])) {
                    unset($item['id'], $item['title']);
                    $data[$activity_id]['child'][] = $item;
                } else {
                    $data[$item['id']] = [
                        'id' => $item['id'],
                        'title' => $item['title'],
                    ];
                    unset($item['id'], $item['title']);
                    $data[$activity_id]['child'] = [$item];
                }
            }

            return JsonReturnInfo::infoSuccess('获取数据成功.', array_values($data));

        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 获取所有参加了某个用户发布的调查的参与者
     * 也就是根据 user_id 获取 participant_id
     * 怎么分组？每一期调查的参与者信息，还是参与者参加了那几期调查？
     * 暂时按前者处理。总体分成活动/调查两个部分。
     *
     * @param $user_id int|string 当前登录用户的 user_id
     * @return array
     */
    public function getSurveyParticipantsByUserId($user_id = 0)
    {
        if (Helper::idInvalid($user_id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 根据 user_id 查询 survey_id，再根据 survey_id 查询参与者的 participants 信息
            $result = Participant::getByUserId($user_id, 'survey'); //->toArray();

            $data = [];
            foreach ($result as $item) {
                $item = json_decode(json_encode($item), true);
                $survey_id = $item['id'];
                if (isset($data[$item['id']])) {
                    unset($item['id'], $item['title']);
                    $data[$survey_id]['child'][] = $item;
                } else {
                    $data[$item['id']] = [
                        'id' => $item['id'],
                        'title' => $item['title'],
                    ];
                    unset($item['id'], $item['title']);
                    $data[$survey_id]['child'] = [$item];
                }
            }

            return JsonReturnInfo::infoSuccess('获取数据成功.', array_values($data));
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 获取所有参加了某个用户发布的活动和调查的参与者
     * 也就是根据 user_id 获取 participant_id
     * 怎么分组？每一期调查的参与者信息，还是参与者参加了那几期活动和调查？
     * 暂时按前者处理。总体分成活动/调查两个部分。
     *
     * @param $user_id int|string 当前登录用户的 user_id
     * @return array
     */
    public function getParticipantsByUserId($user_id = 0)
    {
        if (Helper::idInvalid($user_id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 根据 user_id 查询 activity_id，再根据 activity_id 查询参与者的 participants 信息
            $activityResult = Participant::getByUserId($user_id, 'activity'); //->toArray();
            $activityData = [];
            foreach ($activityResult as $item) {
                $item = json_decode(json_encode($item), true);
                $survey_id = $item['id'];
                if (isset($activityData[$item['id']])) {
                    unset($item['id'], $item['title']);
                    $activityData[$survey_id]['child'][] = $item;
                } else {
                    $activityData[$item['id']] = [
                        'id' => $item['id'],
                        'title' => $item['title'],
                        // 'type' => 'activity',
                    ];
                    unset($item['id'], $item['title']);
                    $activityData[$survey_id]['child'] = [$item];
                }
            }
            $activityData = array_values($activityData);


            // 根据 user_id 查询 survey_id，再根据 survey_id 查询参与者的 participants 信息
            $surveyResult = Participant::getByUserId($user_id, 'survey'); //->toArray();
            $surveyData = [];
            foreach ($surveyResult as $item) {
                $item = json_decode(json_encode($item), true);
                $survey_id = $item['id'];
                if (isset($surveyData[$item['id']])) {
                    unset($item['id'], $item['title']);
                    $surveyData[$survey_id]['child'][] = $item;
                } else {
                    $surveyData[$item['id']] = [
                        'id' => $item['id'],
                        'title' => $item['title'],
                        // 'type' => 'survey',
                    ];
                    unset($item['id'], $item['title']);
                    $surveyData[$survey_id]['child'] = [$item];
                }
            }
            $surveyData = array_values($surveyData);

            return JsonReturnInfo::infoSuccess('获取数据成功.', [
                'acitivity' => $activityData,
                'survey' => $surveyData,
            ]);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }
}